package com.example.lib.extend

import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import java.math.BigDecimal
import kotlin.math.pow
import androidx.core.net.toUri

//如果最后一个字符
fun String?.removeLastComma(symbol: String = ","): String {
    return if (isNullOrEmpty()) ""
    else {
        if (this.endsWith(symbol)) {
            substring(0, length - 1)
        } else this
    }
}

fun String?.version(): BigDecimal {
    if (isNullOrEmpty()) return BigDecimal.ZERO
    val split = split(".")
    val versionText = split.joinToString("")
    return versionText.autoDouble().toBigDecimal().divide(10.0.pow(versionText.length).toBigDecimal())
        .setScale(versionText.length)
}

fun String.getUrlParams(params: String): String {
    val parse = "https://test?$this".toUri()
    return parse.getQueryParameter(params) ?: ""
}

fun String.isEmail(): Boolean {
    val emailPattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
    return matches(emailPattern.toRegex())
}

/**
 * 改变一段文字部分文字颜色
 * 暂未添加点击事件
 * @param start
 * 开始位置
 * @param size
 * 文字长度
 * @param color
 * 颜色
 * @return Spannable
 */
fun String.getTextSpan(start: Int, size: Int, color: Int): SpannableString {
    val spannableString = SpannableString(this)
    val colorSpan = ForegroundColorSpan(color)
    spannableString.setSpan(colorSpan, start, start + size, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
    return spannableString
}

fun String?.isTrue() = if (isNullOrEmpty()) false else this == "1"

